package com.one.controller;

import com.one.annotation.RequestPermission;
import com.one.annotation.RequestUser;
import com.one.constant.RedisPrefixConstant;
import com.one.constant.RequestReturnConstant;
import com.one.constant.WechatPayConstant;
import com.one.service.FlashSaleOrderService;
import com.one.service.OrderFlashSaleService;
import com.one.service.WechatPayService;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.vo.ProductParamVo;
import com.one.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;


/**
 * Create on 2022-01-16
 * <p>
 * Author: LiangWei
 * <p>
 * Description: 下单和抢购业务接口
 **/
@RestController
@Slf4j
public class OrderFlashSaleController {

    @Autowired
    private OrderFlashSaleService orderFlashSaleService;

    @Autowired
    private FlashSaleOrderService flashSaleOrderService;

    @Autowired
    private WechatPayService wechatPayService;

    @PostMapping("/orderFlashSale")
    @RequestPermission
    public RequestReturn<String> orderFlashSale(@RequestUser UserVo userVo,@RequestBody ProductParamVo productParamVo){
        //TODO 校验用户登录
        //同步库存到redis
        orderFlashSaleService.initProdStockToRedis(productParamVo.getProdId().toString());
        //锁定购买用户，整个抢购流程中只能抢购一件
        if(!orderFlashSaleService.lockFlashSaleUserProd(userVo.getUserId().toString(),productParamVo.getProdId().toString())){
            return RequestReturnFactory.fail(RequestReturnConstant.FLASH_SALE_ONLY_BUY_ONCE_CODE,RequestReturnConstant.FLASH_SALE_ONLY_BUY_ONCE_MSG,null);
        }
        //判断库存锁是否已经释放
        while (true){
            //能够锁库存就跳出循环
            if(orderFlashSaleService.checkProdStockLocked(productParamVo.getProdId().toString())){
                break;
            }
        }
        //判断库存是否充足，如果不充足，是不释放锁？暂时先释放锁
        if(!orderFlashSaleService.checkProdStockEnough(productParamVo.getProdId().toString())){
            orderFlashSaleService.releaseProdStockLocked(productParamVo.getProdId().toString());
            return RequestReturnFactory.fail(RequestReturnConstant.STOCK_NOT_ENOUGH_CODE,RequestReturnConstant.STOCK_NOT_ENOUGH_MSG,null);
        }
        //下单操作，获取生成的订单，执行下单操作前需要判断商品是否是活动商品
        //下单操作
        //返回统一返回信息，包含订单号
        RequestReturn<String> createOrderResult = flashSaleOrderService.createFlashSaleTradeOrder(userVo.getUserId(),productParamVo);
        Integer code = createOrderResult.getCode();
        if(code == 7001 || code == 7002) {
            return createOrderResult;
        }
        while(true) {
            int orderStatus = orderFlashSaleService.getTradeOrderStateFromRedis(RedisPrefixConstant.ORDER_NO+String.valueOf(userVo.getUserId())+":"+createOrderResult.getData());
             if(orderStatus == 1){
                 break;
            }
        }
        //订单生成成功，减库存
        orderFlashSaleService.subProdStockCount(productParamVo.getProdId().toString(),1);
        //释放库存锁
        orderFlashSaleService.releaseProdStockLocked(productParamVo.getProdId().toString());
        return RequestReturnFactory.success(RequestReturnConstant.RETURN_SUCCESS_CODE,RequestReturnConstant.CREATE_ORDER_SUCCESS_MSG,createOrderResult.getData());
    }

    @GetMapping("/wxPay")
    @RequestPermission
    public RequestReturn<String> wxPay(@RequestParam Integer userId,
                                       @RequestParam String orderNo,
                                       @RequestParam Integer consigneeId,
                                       @RequestParam Integer ticketId,
                                       @RequestParam String token) throws Exception {
        if(!wechatPayService.judgeTicketFull(orderNo,ticketId)){
            return RequestReturnFactory.fail(RequestReturnConstant.TICKET_NOT_USE_CODE,RequestReturnConstant.TICKET_NOT_USE_MSG,null);
        }
        //判断总订单是否是待支付状态
        if(!wechatPayService.judgeOrderWaitPay(orderNo)){
            return RequestReturnFactory.fail(RequestReturnConstant.PAY_ORDER_ERROR_CODE,RequestReturnConstant.PAY_ORDER_ERROR_MSG,null);
        }
        //计算总金额
        Integer totalFee = wechatPayService.getTruePrice(orderNo,ticketId);


        // 生成到微信官方统一下单的请求xml参数字符串
        String unifiedOrderParamsXml = wechatPayService.wechatPayUnifiedOrderParamsXml(userId,token,orderNo,consigneeId,totalFee,ticketId);
        // 发送统一下单请求
        Map<String,String> unifiedOrderReturnMap = wechatPayService.wechatPayUnifiedOrder(unifiedOrderParamsXml);
        log.info("微信返回参数：{}",unifiedOrderReturnMap);
        // 自定义返回结果集合
        // Map<String, String> unifiedOrderResultMap = new HashMap<>();
        if(WechatPayConstant.WECHAT_PAY_RETURN_CODE_SUCCESS.equals(unifiedOrderReturnMap.get("return_code"))
                &&WechatPayConstant.WECHAT_PAY_RESULT_CODE_SUCCESS.equals(unifiedOrderReturnMap.get("result_code"))){
            return RequestReturnFactory.success(RequestReturnConstant.RETURN_SUCCESS_CODE,RequestReturnConstant.GET_ORDER_URL_SUCCESS_MSG,unifiedOrderReturnMap.get("code_url"));
        }
        return RequestReturnFactory.fail(RequestReturnConstant.GET_ORDER_URL_FAIL_CODE,RequestReturnConstant.GET_ORDER_URL_FAIL_MSG,null);
    }

    /**
     *@author : LiangWei
     *@date : 2022-01-04 16:51
     *@return :
     *@description : 接收微信官方支付结果回调
     */
    @RequestMapping("/unifiedNotify")
    public void wechatPayUnifiedNotify(HttpServletRequest request, HttpServletResponse response){
        //获取微信异步通知结果
        try(InputStream inputStream = request.getInputStream()){
            //读取流数据
            BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            //定义读取临时变量
            String readLine = "";
            //定义保持数据的可变字符串对象
            StringBuilder unifiedNotifyResultXml = new StringBuilder();
            //循环读取返回结果
            while((readLine = bfr.readLine())!=null){
                unifiedNotifyResultXml.append(readLine);
            }
            log.info("------3。微信异步通知结果：{}------",unifiedNotifyResultXml);
            //解析异步通知结果
            String unifiedNotifyResponseXml = wechatPayService.wechatPayUnifiedNotifyResole(unifiedNotifyResultXml.toString());

            //同步返回给微信官方处理结果
            PrintWriter out = response.getWriter();
            out.write(unifiedNotifyResponseXml);
            out.flush();
            out.close();
            log.info("------4.微信异步通知，同步返回结果：{}------",unifiedNotifyResponseXml);

        }catch (Exception e){
            log.warn("------5.微信异步通知处理异常，异常信息为：{}------",e.getMessage());
        }
    }
}

